﻿using System.Collections.Generic;
using System.Windows.Forms;

namespace zaklad_rtv
{
    public class PrintableConfirmation
    {
        private string _html;
        private WebBrowser _webBrowser;

        public PrintableConfirmation(PrintType type, Dictionary<string, string> data)
        {
            PrepareWebBrowser();
            ReadTemplate(type);
            ReplaceVariableData(data);
        }

        private void PrepareWebBrowser()
        {
            _webBrowser = new WebBrowser();
            _webBrowser.DocumentCompleted += HTMLLoaded;
            ClearBrowserPrintHeaderAndFooter();
        }

        private void HTMLLoaded(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            _webBrowser.ShowPrintDialog();
        }

        private void ReadTemplate(PrintType type)
        {
            switch (type)
            {
                case PrintType.Ticket:
                    _html = Properties.Resources.TicketHTML;
                    break;
                case PrintType.FinalSummary:
                    _html = Properties.Resources.FinalHTML;
                    break;
            }
        }

        private void ReplaceVariableData(Dictionary<string, string> data)
        {
            foreach (var entry in data)
            {
                _html = _html.Replace(entry.Key, entry.Value);
            }
        }

        public void PrintConfirmation()
        {
            _webBrowser.DocumentText = _html;
        }

        private void ClearBrowserPrintHeaderAndFooter()
        {
            const string registryKeyPath = "Software\\\\Microsoft\\\\Internet Explorer\\\\PageSetup";
            var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(registryKeyPath, true) ??
                      Microsoft.Win32.Registry.LocalMachine.OpenSubKey(registryKeyPath, true);
            if (key != null)
            {
                key.SetValue("header", "");
                key.SetValue("footer", "");
                key.Close();
            }
        }
    }
}
